/**
 * Module dependencies.
 */

var express = require('express'),
  routes = require('./routes'),
  user = require('./routes/user'),
  http = require('http'),
  https = require('https'),
  url = require('url'),
  path = require('path'),
  fs = require('fs'),
  Client = require('./lib/client');
var client = Client.getInstance();
// var WebSocket = require('faye-websocket');
var app = express();

// all environments
app.set('http_port', process.env.PORT || 3000);
app.set('https_port', process.env.PORT || 8000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', function(req, res) {
  // if (req.cookies.user == null) {
  //   res.redirect('/signin');
  // } else {
  res.sendfile('views/index.html');
  // }
});
app.get('/signin', function(req, res) {
  res.sendfile('views/signin.html');
});
app.post('/signin', function(req, res) {
  if (users[req.body.name]) {
    //存在，则不允许登陆
    res.redirect('/signin');
  } else {
    //不存在，把用户名存入 cookie 并跳转到主页
    res.cookie("user", req.body.name, {
      maxAge: 1000 * 60 * 60 * 24 * 30
    });
    res.redirect('/');
  }
});

// add by seekei
app.get('/start', function(req, res) {
  res.sendfile('views/start.html');
});

app.get('/template', function(req, res) {
  res.sendfile('views/template.html');
});

// 创建任务
app.post('/api/task/build', function(req, res) {
  var setting = req.body;
  console.log(client, setting);
  client.buildTask(setting, function(err, result) {
    console.log('进入');
    res.type('json');
    if (!err) {
      res.send({
        'msg': result
      });
    } else
      res.send({
        'msg': err
      });
  });
});

// 立刻启动任务
app.post('/api/task/start', function(req, res) {
  var setting = req.body;
  var id = 0;
  client.start(id, function(err, result) {
    res.type('json');
    if (!err) {
      res.send({
        'msg': result
      });
    } else
      res.send({
        'msg': err
      });
  });
});

// 暂停任务
// 暂未测试返回结果
app.post('/api/task/stop', function(req, res) {
  var id = req.body.id;
  client.stopTask(id, function(err, result) {
    res.type('json');
    if (!err) {
      res.send({
        'msg': result
      });
    } else
      res.send({
        'msg': err
      });
  });
});

// 查看任务状态
app.get('/api/task/getStatus', function(req, res) {
  // var setting = req.body;
  // 查看所有任务的状态
  client.getStatus(function(err, result) {
    res.type('json');
    if (!err) {
      res.send(result);
    } else
      res.send(err);
  })
});

// 删除任务状态
app.post('/api/task/delete', function(req, res) {
  var setting = req.body;
  var id = req.body.id;
  client.deleteTask(id, function(err, result) {
    res.type('json');
    if (!err) {
      res.send(result);
    } else {
      res.send(err);
    }
  });
});

// 周期任务列表
app.post('/api/task/list', function(req, res) {
  var setting = req.body;
  // 获取所有的task
  // normalList timerList
  client.getList(function(err, result) {
    res.type('json');
    if (!err) {
      // r.success = true;
      return res.send(result);
      // res.json(result);
    } else
      res.send({
        'msg': err
      });

    // res.json({
    //   'msg': err
    // });


  });
});

// 修改task配置
app.post('/api/task/update', function(req, res) {
  var setting = req.body.setting;
  var taskId = req.body.taskId;
  client.updateTask(taskId, setting, function(err, result) {
    res.type('json');
    if (!err) {
      return res.send(result);
    } else {
      res.send({
        'msg': err
      });
    }
  })
});


var server = http.createServer(app);
var ioServer = require('socket.io');
var io = new ioServer()


// io.sockets.on('connection', function(socket) {

//   socket.on('new url', function(data) {
//     console.log('data是', data);
//     // console.log(data.url.protocol);
//     console.log(data.url);
//     var urlObj = url.parse(data.url);
//     var protocol = http;
//     // console.log(protocol);
//     if (urlObj.protocol == 'https:') {
//       protocol = https;
//     }
//     protocol.get(data.url, function(res) {
//       var html = '';
//       res.on('data', function(d) {
//         html += d;
//       });
//       res.on('end', function() {
//         console.log('完成');
//         fs.writeFile('views/default.html', html, function(err) {
//           if (err) {
//             console.log('写文件出现错误');
//             socket.emit('new webpage', {
//               success: false,
//               message: err
//             });
//           }
//           console.log('已写到default.html中');
//           socket.emit('new webpage', {
//             success: true
//           });
//         })
//       });
//     }).on('error', function(err) {
//       socket.emit('new webpage', {
//         success: false,
//         message: err
//       });
//       console.log('错误信息：' + err);
//     });

//     //后端返回的数据在这可以模拟
//     // resData = {
//     //   // url:'http://www.wanfangdata.com.cn'
//     //   url: data.url
//     // }
//     // socket.emit('new webpage', resData);

//     // add by seekei
//     // 获取页面并且写到default.html中

//   })
// });

//add by lee
app.get('/origin', function(req, res) {
  res.sendfile('views/origin.html');
});
app.get('/mirror', function(req, res) {
  res.sendfile('views/mirror.html');
});

var messages = [];
var receivers = [];
var projector;
var now_receiver;

// //add by lee
// var projector2 = io
//   .of('/projector')
//   .on('connection', function (socket) {
// console.log('projector connection initiating.');

//     if (projector) {
//       console.log('closing existing projector. setting messages to 0');
//       projector.disconnect();
//       messages.length = 0;
//     }

//     projector = socket;

//     messages.push(JSON.stringify({ clear: true }));

//     receivers.forEach(function(socket) {
//       socket.emit('receiver',messages[0]);
//     });


//     socket.on('projector',function(data) {
//       console.log('message received. now at ' + messages.length + ' . sending to ' + receivers.length);
//       receivers.forEach(function(receiver) {
//         receiver.emit('receiver',data);
//       });

//       messages.push(data);
//     });

//     socket.on('disconnect', function() {
//       console.log('projector closing, clearing messages');
//       messages.length = 0;
//       receivers.forEach(function(socket) {
//         socket.emit('receiver',JSON.stringify({ clear: true }));
//       });

//       projector = undefined;
//     });
//   });

// var receiver2 = io
//   .of('/receiver')
//   .on('connection', function (socket) {
//     console.log('receiver connection')
//     receivers.push(socket);

//     console.log('receiver opened. now at ' + receivers.length + ' sending ' + messages.length + ' messages');
//     socket.emit('receiver',JSON.stringify(messages));


//     socket.on('disconnect', function() {
//       var index = receivers.indexOf(socket);
//       receivers.splice(index, 1);
//       console.log('receiver closed. now at ' + receivers.length);
//     });


//   });

var privateKey = fs.readFileSync('./keys/private.pem', 'utf8');
var certificate = fs.readFileSync('./keys/file.crt', 'utf8');
var credentials = {
  key: privateKey,
  cert: certificate
};



// var httpServer = http.createServer(app);
// var httpsserver = https.createServer(credentials, app);

// var options = {
//   key: fs.readFileSync('./keys/server-key.pem'),
//   ca: [fs.readFileSync('./keys/ca-cert.pem')],
//   cert: fs.readFileSync('./keys/server-cert.pem')
// };

// var options = {
//   key: fs.readFileSync('./cakey.pem'),
//   cert: fs.readFileSync('./cacert.pem'),
//   requestCert: false,
//   rejectUnauthorized: false
// };
var httpsserver = https.createServer(credentials, app);
httpsserver.listen(app.get('https_port'), function() {
  console.log('Express http_server listening on port ' + app.get(
    'https_port'));
});



server.listen(app.get('http_port'), function() {
  console.log('Express server listening on port ' + app.get('http_port'));
});
io.attach(httpsserver);
io.attach(server);
//add by lee
var projector2 = io
  .of('/projector')
  .on('connection', function(socket) {
    console.log('projector connection initiating.');
    // if (now_receiver) {
    //   now_receiver.disconnect();
    //   console.log('now_receiver disconnect');
    // }

    if (projector) {
      console.log('closing existing projector. setting messages to 0');
      projector.disconnect();
      messages.length = 0;
    }

    projector = socket;

    messages.push(JSON.stringify({
      clear: true
    }));

    receivers.forEach(function(socket) {
      socket.emit('receiver', messages[0]);
    });


    socket.on('projector', function(data) {
      console.log('message received. now at ' + messages.length +
        ' . sending to ' + receivers.length);
      receivers.forEach(function(receiver) {
        receiver.emit('receiver', data);
      });
      console.log(data, 'data');

      messages.push(data);
    });

    socket.on('disconnect', function() {
      console.log('projector closing, clearing messages');
      messages.length = 0;
      receivers.forEach(function(socket) {
        socket.emit('receiver', JSON.stringify({
          clear: true
        }));
      });

      projector = undefined;
    });
  });

var receiver2 = io
  .of('/receiver')
  .on('connection', function(socket) {
    console.log('receiver connection')
    receivers.push(socket);
    // now_receiver = socket;
    console.log('receiver opened. now at ' + receivers.length + ' sending ' +
      messages.length + ' messages');
    socket.emit('receiver', JSON.stringify(messages));
    // console.log(JSON.stringify(messages), 'messages');

    socket.on('disconnect', function() {
      var index = receivers.indexOf(socket);
      receivers.splice(index, 1);
      console.log('receiver closed. now at ' + receivers.length);
    });


  });
